import numpy as np
import cv2
from PIL import Image, ImageFilter


def bilateral_filter_own(image, d, sigma_color, sigma_space):
    # 创建输出图像
    filtered_image = np.zeros_like(image)

    # 计算高斯空间
    gaussian_space = np.zeros((d, d))
    for i in range(d):
        for j in range(d):
            x = i - (d - 1) / 2
            y = j - (d - 1) / 2
            gaussian_space[i, j] = np.exp(-(x ** 2 + y ** 2) / (2 * sigma_space ** 2))

    # 遍历每个颜色通道
    for channel in range(image.shape[2]):
        # 遍历像素点计算
        for row in range(image.shape[0]):
            for col in range(image.shape[1]):
                # 构建每一次选取的框大小
                left = max(col - (d - 1) // 2, 0)
                right = min(col + (d - 1) // 2, image.shape[1] - 1)
                top = max(row - (d - 1) // 2, 0)
                bottom = min(row + (d - 1) // 2, image.shape[0] - 1)

                # 获取周边像素
                region = image[top:bottom + 1, left:right + 1, channel]

                # 计算颜色空间
                gaussian_color = np.exp(-((region - image[row, col, channel]) ** 2) / (2 * sigma_color ** 2))

                # 应用双边滤波
                g_space_cropped = gaussian_space[(top - row + (d - 1) // 2):(bottom - row + (d - 1) // 2 + 1),
                                  (left - col + (d - 1) // 2):(right - col + (d - 1) // 2 + 1)]
                total_weight = np.sum(gaussian_color * g_space_cropped)
                filtered_value = np.sum(region * gaussian_color * g_space_cropped) / total_weight

                filtered_image[row, col, channel] = int(np.round(filtered_value))

    return filtered_image


diameter = 8
sigma_color_value = 100.0
sigma_space_value = 100.0

input_image = cv2.imread('img.png')

output_image_own = bilateral_filter_own(input_image, diameter, sigma_color_value, sigma_space_value)

output_image_cv2 = cv2.bilateralFilter(input_image, diameter, sigma_color_value, sigma_space_value)

cv2.imwrite('../data/bilateral_own.png', output_image_own)
cv2.imwrite('../data/bilateral_cv2.png', output_image_cv2)

# 高斯滤波
gaussian_blurred = cv2.GaussianBlur(input_image, (5, 5), 0)
cv2.imwrite('../data/gaussian_blurred.png', gaussian_blurred)

# 中值滤波 Filter
median_blurred = cv2.medianBlur(input_image, 5)
cv2.imwrite('../data/median.png', median_blurred)

# 均值滤波
blurred = cv2.blur(input_image, (9, 9))
cv2.imwrite('../data/blur.png', blurred)


# 打开一个图像文件
image = Image.open("img.png")

# 应用模糊滤波器
blurred_image = image.filter(ImageFilter.BLUR)
blurred_image.save("./data/pllow_blur.png")

# 应用锐化滤波器
sharpened_image = image.filter(ImageFilter.SHARPEN)
sharpened_image.save("./data/pillow_sharpen_blur.png")
# 应用边缘增强滤波器
edge_enhanced_image = image.filter(ImageFilter.EDGE_ENHANCE)
edge_enhanced_image.save("./data/pillow_edge_enhanced_blur.png")

# 应用细节滤波器
detailed_image = image.filter(ImageFilter.DETAIL)
detailed_image.save("./data/pillow_detailed_blur.png")